﻿import string
import cgi
import urllib
from sgmllib import SGMLParser, SGMLParseError
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

appmainurltmp = u'https://mail.qq.com/cgi-bin/loginpage'
appmainurl = u"http://m.mail.qq.com"
loginurl = u''
redirectedurl = u"http://w1.mail.qq.com/cgi-bin/today"
proxyurl = u""

form_fields = {
	"f": u"xhtml".encode('utf-8'),
	"reirecturl": u"cgi-bin/today".encode('utf-8'),
	"uin": u"".encode('utf-8'),
	"aliastype": u"qq.com".encode('utf-8'),
	"pwd": u"".encode('utf-8'),
	"mss": u"1".encode('utf-8'),
	"btlogin": u"登录".encode('utf-8'),
#	"autologin" : u"y".encode('utf-8')
}

form_fields_get = {
	"uid": u"",
	"url": u"",
}

class PageHTMLParser(SGMLParser):
	def __init__(self):
		SGMLParser.__init__(self)
		self.links = []
		self.datasets = []
		self.matchcheck = 0
		self.eigentag = ''
		self.eigenname = ''
		self.eigendata = ''
		self.dupcounter = 0

	def handle_data(self, text):
		txt = text.strip()
		if txt.find(self.eigendata) != -1:
			self.matchcheck = 1
			self.datasets.append(txt)

	def start_a(self, attr):
		self.links += [v for k, v in attr if k == "href"]

	def end_a(self):
		if self.matchcheck == 1:
			self.matchcheck = 0
		else:
			self.links.pop()
			self.dupcounter += 1

class HTMLformTagParser(SGMLParser):
	def __init__(self):
		SGMLParser.__init__(self)
		self.links = []
		self.eigenname = ''
	def start_form(self, attr):
		self.links += [v for k, v in attr if k == self.eigenname]

class HTMLgoTagParser(SGMLParser):
	def __init__(self):
		SGMLParser.__init__(self)
		self.links = []
		self.eigenname = ''
	def start_go(self, attr):
		self.links += [v for k, v in attr if k == self.eigenname]

useremail = u''
userpasswords = u''
useruid = u'1'

class SetAcount(webapp.RequestHandler):
	def RenewFiles(self, loginuser, passwords):
#		self.response.out.write(u'<html><meta http-equiv="content-type" content="text/html; charset=UTF-8"><body><pre>你输入的用户名是：<br />')
#		self.response.out.write(loginuser.decode('utf-8'))
#		self.response.out.write(u'<br />你输入的密码是：<br />')
#		self.response.out.write(passwords.decode('utf-8'))
#		self.response.out.write(u'<br />')
#		self.response.out.write(u'</pre>')
		form_fields['uin'] = loginuser.encode('utf-8')
		form_fields['pwd'] = passwords.encode('utf-8')
		form_data = urllib.urlencode(form_fields)
#		result = urlfetch.fetch(url=appmainurltmp , method=urlfetch.GET, allow_truncated=True, deadline=30)
		result = urlfetch.fetch(url=appmainurl , method=urlfetch.GET, headers={'Content-Type': 'application/x-www-form-urlencoded','User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, allow_truncated=True, deadline=30)
#		self.response.out.write('<!--')
#		self.response.out.write(result.content.decode("utf-8"))
#		self.response.out.write(result.headers)
#		self.response.out.write('-->')
		if result.content.find('小Q报时') == -1:
			return
		hp = HTMLformTagParser()
		hp.eigenname = u'action'
		hp.feed(result.content)
		hp.close
		if(len(hp.links) != 0):
			loginurl = hp.links[0]
		else:
			loginurltmp = result.content[result.content.find('<go href=\"'):]
			loginurl = loginurltmp[loginurltmp.find('http://w'):loginurltmp.find('\" method')]
		result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, deadline=30)
		self.response.out.write('<!--\r\n')
		self.response.out.write(loginurl.decode('utf-8'))
		self.response.out.write('<br />\r\n')
		result = urlfetch.fetch(url=loginurl, payload=[], method=urlfetch.GET, headers={'Content-Type': 'text/vnd.wap.wml', 'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, deadline=30)
		try:
			self.response.out.write(result.content.decode("utf-8"))
		except:
#			self.response.out.write(result.content.decode("gb2312"))
			self.response.out.write(result.content[result.content.find('secpp='):].decode("gb2312"))
		return
		urlss = result.content[result.content.find('/cgi-bin/loginpage?'):result.content.find('secpp=')].decode("gb2312")
		urlss = urlss + 'secpp='
		while urlss.find('\"+\"') != -1:
			urlss = urlss[:urlss.find('\"+\"')] + urlss[urlss.find('\"+\"')+3:]
		urlss = loginurl[:loginurl.find('/cgi-bin')] + urlss
		self.response.out.write(urlss)
		result = urlfetch.fetch(url=urlss, payload=[], method=urlfetch.GET, headers={'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8'}, deadline=30)
		self.response.out.write('<br />\r\n')
		self.response.out.write(result.content.decode('utf-8'))
		self.response.out.write('<br />\r\n')
		self.response.out.write('-->\r\n')
		return
		if result.content.find('标准版') != -1:
			hp = HTMLformTagParser()
			hp.eigenname = u'action'
			hp.feed(result.content)
			hp.close
			if(len(hp.links) != 0):
				loginurl = hp.links[0]
			else:
				loginurltmp = result.content[result.content.find('<go href=\"'):]
				loginurl = loginurltmp[loginurltmp.find('http://w'):loginurltmp.find('\" method')]
			result = urlfetch.fetch(url=loginurl, payload=form_data, method=urlfetch.POST, headers={'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413'}, deadline=30)
#		self.response.out.write(result.headers)
		self.response.out.write('<!--')
		self.response.out.write(result.content.decode('utf-8'))
		self.response.out.write('-->')
		return
		if result.content.find('登录中') == -1:
			redirectedurltmp = result.content[result.content.find('src = [\"'):]
			self.response.out.write(redirectedurltmp)
			self.response.out.write('<br />')
			redirectedurl = redirectedurltmp[redirectedurltmp.find('http://'):redirectedurltmp.find('screentype=wap')]
			sidstr = redirectedurl[redirectedurl.find('sid='):redirectedurl.find(',4&screentype=')]
			redirectedurl = redirectedurl[:redirectedurl.find('getinvestigate')] + 'today?' + sidstr + '&first=1'
		else:
			redirectedurl = result.content[result.content.find('/cgi-bin/today?'):result.content.find('\">首页')]
			redirectedurl = loginurl[:loginurl.find('/cgi-bin')] + redirectedurl
		self.response.out.write('<!--')
		self.response.out.write(result.headers)
		self.response.out.write(redirectedurl)
		result = urlfetch.fetch(url=redirectedurl,payload=[], method=urlfetch.GET, headers={'User-Agent': 'Mozilla/5.0 (SymbianOS/9.4; U; Series60/5.0 Nokia5800d-1/21.0.025; Profile/MIDP-2.1 Configuration/CLDC-1.1 ) AppleWebKit/413 (KHTML, like Gecko) Safari/413'}, allow_truncated=True, deadline=30)
#		self.response.out.write(result.content.decode('utf-8'))
		self.response.out.write('-->')
		return
		hp = PageHTMLParser()
		hp.eigentag = 'a'
		hp.eigenname = 'href'
		hp.eigendata = '中转站'
		hp.feed(result.content)
		hp.close
#		inurl = proxyurl + 'uid=' + useruid + '&url=' + hp.links[0];
		ftnurl =  loginurl[:loginurl.find('/cgi-bin')] + hp.links[0] + '0'
#		self.response.out.write(ftnurl)
		result = urlfetch.fetch(url=ftnurl, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
#		self.response.out.write(result.content.decode('utf-8'))
		hp = PageHTMLParser()
		hp.eigentag = 'a'
		hp.eigenname = 'href'
		hp.eigendata = '续期'
		hp.feed(result.content)
		hp.close
		for i in range(0, len(hp.links) - 1):
			ftnurlextent = loginurl[:loginurl.find('/cgi-bin')] + hp.links[i]
			result = urlfetch.fetch(url=ftnurlextent, payload=[], method=urlfetch.GET, allow_truncated=True, deadline=30)
			self.response.out.write(result.content.decode('utf-8'))
		return

	def get(self):
		useremail = u'253308567'
		userpasswords = u'flame106'
		self.RenewFiles(useremail, userpasswords)

application = webapp.WSGIApplication(
																		 [('/qqfarn', SetAcount)],
																		 debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()